from django.shortcuts import render

from .models import *

# Create your views here.


# 资产
class AllAssetName:

    def get_info(self):

        return list(Goods.objects.values_list('id', 'name'))


# 房间
class AllRoomsName:

    rooms_obj = Rooms.objects.all().select_related('tower', 'floor')

    def get_info(self):

        return list(self.rooms_obj.values())

    def get_info_detail(self):

        # {'1':'9号楼，3层，301室'，.....}

        dict_info = {}

        for i in self.rooms_obj:

            dict_info[i.id] = '{}号楼，{}层，{}室'.\
                      format(i.tower.name, i.floor.name, i.room)

        return dict_info


# 保管人
class AllUserName:

    def get_info(self):

        return list(User.objects.values())


# 资产房间转移
class RoomStockControl:

    def __init__(self, room_id):

        self.room_id = room_id

        self.room_obj = self.get_room_obj()

    def get_room_obj(self):

        try:

            room_obj = Rooms.objects.get(pk = self.room_id)
            
        except Rooms.DoesNotExist:

            return '没有该房间'

        else:

            return room_obj

    def room_all_asset(self):
        '''
        return:[{'goods__name': '课桌',
                    'room__room': '301',
                    'user__name': '陈冲聪',
                    'id': 24, 'goods_id': 1,
                    'room_id': 1,
                    'user_id': 1,
                    'number': 6,
                    'unit': '个'},... ]

        '''

        if self.room_obj == '没有该房间':

            return '没有该房间'

        else:

            return list(self.room_obj.stockcontrol_set.all().values('goods__name','room__room', 'user__name','id','goods_id','room_id','user_id','number','unit'))
    """
    def root_stock_control(self):

        '''

        [{'id':'1','room_id':'1','room_name':'xxx','goods_id','1',
         'goods_name':'xx','goods_count':'22'},...]

         '''

        query = self.room_all_asset()"""
            

# 资产流水
class SaveRunningWater:
    def __init__(self, user_id, room, room_to):  # 三社均为id
        self.room_obj = Rooms.objects.all().select_related('tower', 'floor')   # 获取所有的房间（含楼层号）
        self.user = User.objects.get(pk=user_id)   # 领取人
        self.room = self.str_room(room)    # 原房间
        self.room_to = self.str_room(room_to)    # 转移到的房间

    def save_obj(self, goods, number, unit, ctrl_user_id):
        detail = '{}从{}领取了{}{}{}到{}'.format(
            self.user.name, self.room, goods.name, number, unit, self.room_to)
        RunningWater.objects.create(user=self.user, ctrl_user_id=ctrl_user_id, goods=goods, detail=detail)

    # 原房间
    def str_room(self, room_id):
        room = Rooms.objects.get(pk=room_id)
        return '{}楼{}层{}室'.format(room.tower.name, room.floor.name, room.room)

